package cn.wolfcode.realm;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.impl.EmployeeServiceImpl;
import cn.wolfcode.service.impl.PermissionServiceImpl;
import cn.wolfcode.service.impl.RoleServiceImpl;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CrmRealm extends AuthorizingRealm {
   @Autowired
   private EmployeeServiceImpl employeeService ;
   @Autowired
   private PermissionServiceImpl permissionService ;
   @Autowired
   private RoleServiceImpl roleService ;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        System.out.println("--------------------------------");
        Employee employee = (Employee)principal.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if(!UserContext.getCurrentUser().isAdmin()){
            List<String> permissions = permissionService.selectByEmpId(employee.getId());
            info.addStringPermissions(permissions);
            List<String> roles = roleService.selectSnByEmpId(employee.getId());
            info.addRoles(roles);
        }else{
            info.addStringPermission("*:*");
            info.addRole("admin");
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken Token) throws AuthenticationException {
        String username = (String)Token.getPrincipal();
        Employee employee = employeeService.selectByName(username);
        if(employee!=null){
            if(!employee.isStatus()){
                throw new DisabledAccountException("亲,您的账号被禁");
            }
            return new SimpleAuthenticationInfo(employee,employee.getPassword(),this.getName());
        }
        return null;
    }
}
